package sha1;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class dirHash {
    static String result = "";

    public static String DirSHA1(File file) throws FileNotFoundException {
        String filePath = file.getPath();//要计算的文件夹目录
        System.out.println();
        try {
            MessageDigest md5 = MessageDigest.getInstance("SHA-1");
            dfs(filePath);
            if (result.equals("")) {
                //System.out.println(md5.digest(filePath.getBytes()));
                //System.out.println("文件夹为空");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return result;
    }

    public static void dfs(String path) throws Exception {//对文件进行深度优先遍历
        File dir = new File(path);
        File[] fs = dir.listFiles();
        if (fs == null)
            return;
        for (int i = 0; i < fs.length; i++) {
            if (fs[i].isFile()) {
                String temp = SHA1.getHash(path + File.separator + fs[i].getName());
                result = getDigestResult(temp + result, "SHA-1");
                //System.out.printf(fs[i].getName());
                //System.out.println("文件的sha1码为:" + temp + "更新后的结果为:" + result);
            }
            if (fs[i].isDirectory()) {
                dfs(path + File.separator + fs[i].getName());
            }
        }
    }

    public static String getDigestResult(String str, String hashAlgorithm) throws NoSuchAlgorithmException {//用来更新结果
        MessageDigest mDigest = null;
        mDigest = MessageDigest.getInstance(hashAlgorithm);
        mDigest.update(str.getBytes());
        BigInteger bigInt = new BigInteger(1, mDigest.digest());
        String resultStr = bigInt.toString(16);
        return resultStr;
    }
}

